package gzdev;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * 获取数据库的表结构
 */
public class GzDBInfo implements AutoCloseable {

    private Connection connection;

    private String dbName;

    public static final String COLUMN_NAME = "name";
    public static final String IS_KEY = "key";
    public static final String TYPE = "type";

    /**
     * 初始化数据库连接
     *
     * @param params 驱动类、url、用户名、密码
     */
    public GzDBInfo(Map<String, String> params) throws ClassNotFoundException, SQLException {
        // 加载驱动
        Class.forName(params.get(GzConfig.DRIVER_NAME));
        String url = params.get(GzConfig.URL);
        this.connection = DriverManager.getConnection(url, params.get(GzConfig.USERNAME), params.get(GzConfig.PASSWORD));
        // 初始化数据库名称
        // ？符号的位置
        int index = url.lastIndexOf('?');
        this.dbName = url.substring(url.lastIndexOf('/') + 1, index == -1 ? url.length() + 1 : index);
    }

    /**
     * 获取指定表名的表结构
     *
     * @param tableName
     * @return
     */
    public List<Map<String, Object>> getTableStructure(String tableName) {
        List<Map<String, Object>> structure = new ArrayList();
        String sql = "select COLUMN_NAME,DATA_TYPE,COLUMN_KEY from information_schema.COLUMNS WHERE TABLE_SCHEMA like '%s' and TABLE_NAME like '%s'";
        try(ResultSet resultSet = connection.createStatement().executeQuery(String.format(sql, dbName, tableName))){
            while (resultSet.next()) {
                Map<String, Object> column = new HashMap<>();
                column.put(COLUMN_NAME, resultSet.getString(1));
                column.put(TYPE, resultSet.getString(2));
                column.put(IS_KEY,"PRI".equals(resultSet.getString(3)));
                structure.add(column);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return structure;
    }

    /**
     * 获取数据库表名
     *
     * @return 表名的set集合
     */
    public Set<String> getTableNames() throws SQLException {
        Set<String> tableNames = new HashSet<>();
        String sql = "select TABLE_NAME FROM information_schema.TABLES WHERE table_schema like '%s'";
        try (ResultSet resultSet = connection.createStatement().executeQuery(String.format(sql, dbName))) {
            while (resultSet.next())
                tableNames.add(resultSet.getString(1));
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return tableNames;
    }

    @Override
    public void close() throws Exception {
        connection.close();
    }
}
